<template>
    <div class="edit-profile-container">
        <!-- 头部导航栏 -->
        <div class="nav-bar">
            <div class="nav-button cancel" @click="goBack">取消</div>
            <div class="nav-title">编辑个人资料</div>
        </div>

        <!-- 表单区域 -->
        <div class="form-container">
            <div class="form-group">
                <div class="form-label">账号</div>
                <div class="input-wrapper">
                    <input type="text" v-model="userForm.id" class="form-input" readonly>
                </div>
                <div class="readonly-tip">账号不可修改</div>
            </div>

            <div class="form-group">
                <div class="form-label">昵称</div>
                <div class="input-wrapper">
                    <input type="text" v-model="userForm.name" class="form-input" placeholder="请输入">
                </div>
            </div>

            <div class="form-group">
                <div class="form-label">头像</div>
                <el-upload ref="AvatarUploadRef" class="avatar-uploader" :action="path.baseUrl + '/common/upload'" list-type="picture"
                    :auto-upload="false" :show-file-list="false" :data="CoverUploadData" :headers="CoverUploadHeaders"
                    :on-success="handleAvatarSuccess" :on-change="handleChange" :before-upload="beforeAvatarUpload"
                >
                    <img v-if="userForm.avatar" :src="userForm.avatar" alt="用户头像" class="avatar"/>
                    <el-icon v-else class="avatar-uploader-icon">
                        <el-icon><Plus /></el-icon>
                    </el-icon>
                </el-upload>
            </div>

            <div class="form-group">
                <div class="form-label">手机号码</div>
                <div class="input-wrapper">
                    <input type="tel" v-model="userForm.phone" class="form-input" pattern="[0-9]{11}" placeholder="请输入">
                </div>
            </div>

            <div class="form-group">
                <div class="form-label">电子邮箱</div>
                <div class="input-wrapper">
                    <input type="email" v-model="userForm.email" class="form-input" placeholder="请输入">
                </div>
            </div>

            <!-- 提交按钮 -->
            <button type="button" class="submit-button" @click="saveProfile()" :disabled="loading">
                {{ loading ? '保存中...' : '保存修改' }}
            </button>
        </div>
    </div>
</template>

<script lang="ts"0 setup>
import { ref,inject, reactive, onMounted } from 'vue';
import api from '@/api';
import path from "@/api/path.js";
import { ElMessage, ElMessageBox } from 'element-plus';
import type { UploadProps,UploadInstance } from 'element-plus'
import { useRouter } from 'vue-router';
import { UserStore } from '@/stores/userInfoStore';
import { TipStore } from '@/stores/tipStore';

const disableCacheFor = inject('disableCacheFor') as (componentNameList: string[]) => void;
const router = useRouter();
const userStoreObject = UserStore();
const TipStoreObject = TipStore();
const loading = ref(false);

// 表单数据
const userForm = reactive({
    id: userStoreObject.userInfo?.id || null,
    name: userStoreObject.userInfo?.name || null,
    avatar: userStoreObject.userInfo?.avatar || null,
    phone: userStoreObject.userInfo?.phone || null,
    email: userStoreObject.userInfo?.email || null
});

//#region 用户头像上传相关
const AvatarUploadRef = ref<UploadInstance>()
const CoverUploadHeaders = ref({ // 上传时附带的请求头  
    token: ''
})
const CoverUploadData = ref({ // 上传时附带的额外参数
    fullPath: 'img/avatar/',
})
const oldAvatar = ref(null) //原先的头像地址
const isHasNewAvatar = ref(false) //是否上传了新的的头像
const isUploadOver = ref(false) // 是否上传完毕
const handleAvatarSuccess: UploadProps['onSuccess'] = (response,uploadFile) => {
    userForm.avatar = response.data
    //把旧的头像给删掉
    if(oldAvatar.value != null){
        api.deleteObject([oldAvatar.value])
    }
    isUploadOver.value = true
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (!rawFile.type.startsWith('image/')) {
        TipStoreObject.errorTip('头像必须为图片格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 1) {
        TipStoreObject.errorTip('头像大小不能超过 1MB!')
        return false
    }
    return true
}

const handleChange = (file, fileList)=>{
    if(isUploadOver.value == true){ // 如果已经上传完毕，则不执行任何操作(因为文件上传也会触发change事件，不要又把图片地址覆盖掉了)
        return
    }
    userForm.avatar = URL.createObjectURL(file.raw) // 先实现本地预览，未真正上传
    isHasNewAvatar.value = true
}
//#endregion

// 保存个人资料
const saveProfile = async () => {
    try {
        loading.value = true;
        // 1、等待封面上传完毕后再执行下面的步骤
        if(isHasNewAvatar.value == true){
            await new Promise((resolve, reject) => {
                AvatarUploadRef.value!.submit(); //手动上传

                // 定义一个定时器，用于检查是否上传完毕
                const checkInterval = setInterval(() => {
                    if (isUploadOver.value == true) { // 上传成功
                        clearInterval(checkInterval); // 清除定时器
                        isUploadOver.value = false;
                        resolve(userForm.avatar); // resolve 表示上传成功
                    }
                }, 100); // 每隔 100 毫秒检查一次

                // 设置一个超时时间，防止无限等待
                setTimeout(() => {
                    clearInterval(checkInterval); // 清除定时器
                    reject(new Error('图片上传超时')); // 超时后 reject
                    return;
                }, 10000); // 超时时间为 10000 毫秒
            });
        }

        // 2、调用更新接口
        const UpdateRes = await api.updateUser(userForm); 
        if (UpdateRes.data.code == 1) {
            //2.1、先清空原本pinia存储的用户信息
            userStoreObject.cleanUserInfo();
            let userAllInfoRes =  await api.getUserById(userForm.id).then();

            //2.2、更新jwt令牌（重新登陆）
            let jwtRes =  await api.UserLogin(userAllInfoRes.data.data[0].id, null, userAllInfoRes.data.data[0].password)
            localStorage.setItem('wx_access-client', jwtRes.data.data)

            //2.3、解析jwt令牌，在pinia仓库中存入用户信息
            let ParseJwtRes = await api.ParseJwt(jwtRes.data.data).then();
            userStoreObject.setUserInfo(ParseJwtRes.data.data);
            disableCacheFor(['Profile','Works']) //刷新组件的挂载，因为数据更新了

            // 显示成功提示
            ElMessage({
                message: '修改成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                    router.push('/UserDetails');
                }
            });
        } else {
            ElMessage.error(UpdateRes.data.msg || '更新失败');
        }
    } catch (error) {
        console.error('更新用户信息失败:', error);
        ElMessage.error(error.response?.data?.msg || '更新失败，请稍后重试');
    } finally {
        loading.value = false;
    }
};

const goBack = () => {
    router.push('/UserDetails');
};

onMounted(() => {
    oldAvatar.value = userStoreObject.userInfo.avatar;
    CoverUploadHeaders.value.token = localStorage.getItem('wx_access-client')
});

</script>

<style scoped>
.edit-profile-container {
    background-color: #fff;
    min-height: 100vh;
}

.nav-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    background-color: #fff;
    border-bottom: 0.5px solid #e0e0e0;
}

.nav-button {
    font-size: 16px;
    cursor: pointer;
}

.cancel {
    color: #333;
}

.save {
    color: #007aff;
}

.nav-title {
    font-size: 17px;
    font-weight: normal;
    color: #333;
}

.form-container {
    padding: 20px 16px;
}

.form-group {
    margin-bottom: 20px;
}

.form-label {
    font-size: 15px;
    color: #333;
    margin-bottom: 8px;
    margin-left: 4px;
}

.input-wrapper {
    background: #f5f5f5;
    border-radius: 10px;
    padding: 12px 16px;
}

.form-input {
    width: 100%;
    border: none;
    font-size: 15px;
    color: #333;
    background: transparent;
    padding: 0;
}

.form-input::placeholder {
    color: #999;
}

.form-input:focus {
    outline: none;
}

.form-input[readonly] {
    color: #999;
}

.readonly-tip {
    font-size: 12px;
    color: #999;
    margin-bottom: 20px;
    margin-left: 4px;
}

.submit-button {
    width: 100%;
    background-color: #007aff;
    color: white;
    border: none;
    border-radius: 8px;
    padding: 13px 0;
    font-size: 16px;
    font-weight: normal;
    cursor: pointer;
}

.submit-button:disabled {
    background-color: #76b0eb;
    cursor: not-allowed;
}

.avatar-uploader{
    position: relative;
    border: 1px dashed #dcdfe6;
    border-radius: 6px;
    margin-bottom: 10px;
    width: 80px;
    height: 80px;
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.avatar-uploader .avatar {
    width: 80px;
    height: 80px;
    display: block;
    object-fit: cover
}
.el-icon.avatar-uploader-icon {
    position: absolute;
    top: 0;
    left: 0;
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
}
</style>